<?php
App::uses('AppController', 'Controller');
/**
 * Rosters Controller
 *
 * @property Roster $Roster
 */
class RostersController extends AppController {

/**
 * index method
 *
 * @return void
 */
	public function index() {
		$this->Roster->recursive = 0;
		$this->set('rosters', $this->paginate());
                $userId=$this->Session->read('Auth.User.user_id');
                //debug($userId);
                $this->loadModel('Time');
                $time = $this->Time->find('all');
                $this->set(compact('time','userId'));
               //debug($time);
                

	}
        public function feed(){
                // load all rosters (including ones that have been created recently)
                
                //1. Transform request parameters to MySQL datetime format.
                //$mysqlstart = date( 'Y-m-d H:i:s', $this->params['url']['start']);
                //$mysqlend = date('Y-m-d H:i:s', $this->params['url']['end']);

                //2. Get the events corresponding to the time range
                //$conditions = array('Event.start BETWEEN ? AND ?'
                //=> array($mysqlstart,$mysqlend));
                //$events = $this->Event->find('all',array('conditions' =>$conditions));
            
                
                  $uid = CakeSession::read("Auth.User.user_id");
                //debug($uid);
                
                $this->Roster->recursive = 2;
                $rosterArr = $this->Roster->find('all', array('conditions' => array('ros_userid' => $uid)));
                
                // create the json array
                $rows = array();
                
                for($i = 0; $i < count($rosterArr); $i++){
                    // retrieve date from the roster Model
                    $dateRoster = $rosterArr[$i]['Roster']['ros_date'];
                    // time_id  from the roster Model (Comments: Thanks alot Linna for messing up the association)
                    $timeID = $rosterArr[$i]['Roster']['time_id'];
                    // find the corresponding time to and time from FROM the TIME Model
                    $this->loadModel('Time');
                    $timeArr = $this->Time->find('first', array('conditions' => array('id' => $timeID)));
                    // time_from field from the Time Model                                        
                    $timeOfRoster = $timeArr['Time']['time_from'];                                       
                    // concatenate
                    $startDate = $dateRoster . " " .$timeOfRoster;
                    //debug($startDate);
                    
                    //debug($rosterArr[$i]['Roster']);
                    //Create an event entry
                    if($rosterArr[$i]['Roster']['isapprove']){
                        $rows[] = array('id' => $rosterArr[$i]['Roster']['ros_id'],
                        'title' => $timeArr['Time']['time_from'],
                        'start' => $startDate,                    
                        'allDay' => false,

                                'backgroundColor' => '#378006'
                    
                        );
                    }
                    else{
                        $rows[] = array('id' => $rosterArr[$i]['Roster']['ros_id'],
                        'title' => $timeArr['Time']['time_from'],
                        'start' => $startDate,                    
                        'allDay' => false,
                            'backgroundColor' => '#2E84E6'
                        );
                    }
                 }
                    
                    //4. Return as a json array
                    Configure::write('debug', 0);
                    $this->autoRender = false;
                    $this->autoLayout = false;
                    $this->header('Content-Type: application/json');
                    echo json_encode($rows);    
                }
                
                /*
                //3. Create the json array
                $rows = array();
                for ($a=0; count($events)> $a; $a++) {

                //Is it an all day event?
                $all = ($events[$a]['Event']['allday'] == 1);

                //Create an event entry
                $rows[] = array('id' => $events[$a]['Event']['id'],
                'title' => $events[$a]['Event']['title'],
                'start' => date('Y-m-d H:i', strtotime($events[$a]['Event']['start'])),
                'end' => date('Y-m-d H:i',strtotime($events[$a]['Event']['end'])),
                'allDay' => $all,
                );
                }

                //4. Return as a json array
                Configure::write('debug', 0);
                $this->autoRender = false;
                $this->autoLayout = false;
                $this->header('Content-Type: application/json');
                echo json_encode($rows);
                 * 
                 */
                             

                
        

/**
 * view method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function view($id = null) {
		if (!$this->Roster->exists($id)) {
			throw new NotFoundException('Invalid roster','default',array('class'=>'alert alert-danger'));
		}
		$options = array('conditions' => array('Roster.' . $this->Roster->primaryKey => $id));
		$this->set('roster', $this->Roster->find('first', $options));
	}

/**
 * add method
 *
 * @return void
 */
	public function add() {
            $rosters = $this->Roster->User->find('list',array('fields' => array('staff_name')));
            $times = $this->Roster->Time->find('list');
            //$rosters = $this->Roster->User->find('all');
            //debug($rosters);
            //debug($times);
            
		if ($this->request->is('post')) {
			$this->Roster->create();
			if ($this->Roster->save($this->request->data)) {
				//$this->Session->setFlash('The new roster has been saved','default',array('class'=>'alert alert-info'));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash('The new roster could not be saved. Please, try again.','default',array('class'=>'alert alert-danger'));
			}
		}
            $this->set('rosters', $rosters);
            $this->set('times', $times);
	}

/**
 * edit method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function edit($id = null) {
            $rosters = $this->Roster->User->find('list',array('fields' => array('staff_name')));
            $this->set('rosters', $rosters);
		if (!$this->Roster->exists($id)) {
			throw new NotFoundException('Invalid roster','default',array('class'=>'alert alert-danger'));
		}
		if ($this->request->is('post') || $this->request->is('put')) {
			if ($this->Roster->save($this->request->data)) {
				$this->Session->setFlash('The roster has been successfully edited','default',array('class'=>'alert alert-info'));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash('The roster could not be edited. Please, try again.','default',array('class'=>'alert alert-danger'));
			}
		} else {
			$options = array('conditions' => array('Roster.' . $this->Roster->primaryKey => $id));
			$this->request->data = $this->Roster->find('first', $options);
		}
	}

/**
 * delete method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function delete($id = null) {
		$this->Roster->id = $id;
		if (!$this->Roster->exists()) {
			throw new NotFoundException('Invalid roster','default',array('class'=>'alert alert-danger'));
		}
		$this->request->onlyAllow('post', 'delete');
		if ($this->Roster->delete()) {
			$this->Session->setFlash('Roster deleted','default',array('class'=>'alert alert-info'));
			$this->redirect(array('action' => 'index'));
		}
		$this->Session->setFlash('Roster was not deleted','default',array('class'=>'alert alert-danger'));
		$this->redirect(array('action' => 'index'));
	}

/**
 * admin_index method
 *
 * @return void
 */
	public function admin_index() {
		$this->Roster->recursive = 0;
		$this->set('rosters', $this->paginate());
	}

/**
 * admin_view method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function admin_view($id = null) {
		if (!$this->Roster->exists($id)) {
			throw new NotFoundException('Invalid roster','default',array('class'=>'alert alert-danger'));
		}
		$options = array('conditions' => array('Roster.' . $this->Roster->primaryKey => $id));
		$this->set('roster', $this->Roster->find('first', $options));
	}

/**
 * admin_add method
 *
 * @return void
 */
	public function admin_add() {
		if ($this->request->is('post')) {
			$this->Roster->create();
			if ($this->Roster->save($this->request->data)) {
				$this->Session->setFlash('The roster has been saved','default',array('class'=>'alert alert-info'));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash('The roster could not be saved. Please, try again.','default',array('class'=>'alert alert-danger'));
			}
		}
	}

/**
 * admin_edit method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function admin_edit($id = null) {
		if (!$this->Roster->exists($id)) {
			throw new NotFoundException('Invalid roster','default',array('class'=>'alert alert-danger'));
		}
		if ($this->request->is('post') || $this->request->is('put')) {
			if ($this->Roster->save($this->request->data)) {
				$this->Session->setFlash('The roster has been saved','default',array('class'=>'alert alert-info'));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash('The roster could not be saved. Please, try again.','default',array('class'=>'alert alert-danger'));
			}
		} else {
			$options = array('conditions' => array('Roster.' . $this->Roster->primaryKey => $id));
			$this->request->data = $this->Roster->find('first', $options);
		}
	}

/**
 * admin_delete method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function admin_delete($id = null) {
		$this->Roster->id = $id;
		if (!$this->Roster->exists()) {
			throw new NotFoundException('Invalid roster','default',array('class'=>'alert alert-danger'));
		}
		$this->request->onlyAllow('post', 'delete');
		if ($this->Roster->delete()) {
			$this->Session->setFlash('Roster deleted','default',array('class'=>'alert alert-info'));
			$this->redirect(array('action' => 'index'));
		}
		$this->Session->setFlash('Roster was not deleted','default',array('class'=>'alert alert-danger'));
		$this->redirect(array('action' => 'index'));
	}
          public function saveShift(){
                $this->layout = 'ajax';
            $this->autoLayout = false;
            $this->autoRender = false;
            
           
            if($this->request->is('ajax'))
            {
            $shiftPass = $this->request->query;
             $this->Roster->create();
              $userId=$this->Session->read('Auth.User.user_id');
            //$date = date('y-m-d',strtotime($shiftPass['date']));
            //debug($shiftPass);
             
              //ERNEST HERE IS THE VALIDATION PART THAT I AM STUCK
// $this->Roster->find('list', array('conditions' => array('ros_date' => $date, 'time_id' => $time)));
              
            $shift=array(
                'ros_userid'=>$userId,
                'ros_date'=>$shiftPass['date'],
                'time_id'=>$shiftPass['time']                
                    );
            
            
              
           if($this->Roster->save($shift)){
               	$this->Session->setFlash('New Roster has been saved!','default',array('class'=>'alert alert-info'));
                    //debug($shift);
           }  
            }
                    
           
        }
        
        public function beforeFilter() {
            parent::beforeFilter();
            $this->Auth->allow('index', 'view', 'add', 'edit', 'delete','saveShift','feed');
        }
        
      
}
